package com.lapelittle.order.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.lapelittle.framework.common.Result;
import com.lapelittle.framework.model.page.PageResult;
import com.lapelittle.order.entity.SaleOrder;
import com.lapelittle.order.query.SaleOrderQuery;
import com.lapelittle.order.service.SaleOrderImportService;
import com.lapelittle.order.service.SaleOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Tag(name = "销售订单管理")
@RestController
@RequestMapping("/saleOrder")
public class SaleOrderController {
    
    @Autowired
    private SaleOrderImportService importService;
    
    @Autowired
    private SaleOrderService orderService;
    
    @Operation(summary = "导入Excel")
    @PostMapping("/import")
    public Result<String> importExcel(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("请选择要上传的文件");
            }
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
                return Result.error("文件格式错误，请上传Excel文件");
            }
            
            importService.importExcel(file);
            return Result.ok("导入成功");
        } catch (Exception e) {
            return Result.error("导入失败：" + e.getMessage());
        }
    }
    
    @Operation(summary = "分页查询")
    @GetMapping("/list")
    public Result<PageResult<SaleOrder>> list(SaleOrderQuery query) {
        return Result.ok(orderService.queryPage(query));
    }
    
    @Operation(summary = "导出Excel")
    @GetMapping("/export")
    public void export(SaleOrderQuery query, @RequestParam(required = false) String columns, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("销售订单", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        
        // 获取要导出的列
        Set<String> exportColumns = null;
        if (StringUtils.hasText(columns)) {
            exportColumns = new HashSet<>(Arrays.asList(columns.split(",")));
        }
        
        // 查询所有数据（不分页）
        query.setPageSize(Integer.MAX_VALUE);
        List<SaleOrder> list = orderService.queryList(query);
        
        // 创建导出配置
        ExcelWriterBuilder excelBuilder = EasyExcel.write(response.getOutputStream(), SaleOrder.class);
        if (exportColumns != null) {
            excelBuilder.includeColumnFieldNames(exportColumns);
        }
        
        // 写入Excel
        excelBuilder
                .sheet("销售订单")
                .doWrite(list);
    }
} 